<template>
  <div class="_wz_cent_main _wz_insurance_insurance">
    <Card dis-hover :bordered="true" style="margin:0 0 10px;">
      <div slot="extra">
        <Button type="info" size="small" v-if="!searchType" @click="searchType = true" icon="ios-arrow-down">更多</Button>
        <Button type="info" size="small" v-else @click="searchType = false" icon="ios-arrow-up">收起</Button>
      </div>
      <p slot="title">搜索</p>
      <Form :model="formDataSearch" label-position="right" :label-width="100" inline @keydown.native.enter.prevent="">
        <FormItem label="车牌号" v-if="!vehicleData">
          <i-input v-model="formDataSearch.vehiclePlateNo" placeholder="请填写车牌号" clearable />
        </FormItem>
        <FormItem label="车主业户">
          <i-input v-model="formDataSearch.ownerName" placeholder="请填写车主业户" clearable />
        </FormItem>
        <FormItem label="登记人" v-if="searchType">
          <i-input v-model="formDataSearch.registrantName" placeholder="请填写登记人" clearable />
        </FormItem>
        <FormItem label="到期日期" v-if="searchType">
          <DatePicker type="daterange" v-model="dateRange" placeholder="请选择到期日期" style="width:96%"></DatePicker>
        </FormItem>
        <FormItem label="营运车型" v-if="searchType && !vehicleData">
          <i-select v-model="formDataSearch.modelType" filterable placeholder="请选择营运车型" clearable>
            <Option value="1">运输车辆</Option>
            <Option value="2">货运挂车</Option>
          </i-select>
        </FormItem>
        <FormItem label="到期状态" v-if="searchType">
          <i-select v-model="formDataSearch.expireState" filterable placeholder="请选择到期状态" clearable>
            <Option value="1">未到期</Option>
            <Option value="0">已到期</Option>
            <Option value="2">即将到期</Option>
          </i-select>
        </FormItem>
        <FormItem label="提醒状态" v-if="searchType">
          <i-select v-model="formDataSearch.whetherRemind" filterable placeholder="请选择提醒状态" clearable>
            <Option value="1">开启</Option>
            <Option value="0">关闭</Option>
          </i-select>
        </FormItem>
        <FormItem label="保险年份" v-if="searchType">
          <DatePicker type="year" placeholder="请选择保险年份" v-model="formDataSearch.insuranceYearNumber" clearable @on-change="formDataSearch.insuranceYearNumber=$event"></DatePicker>
        </FormItem>
        <FormItem label="运输企业" v-if="searchType && !vehicleData">
          <i-select v-model="formDataSearch.deptUuid" filterable placeholder="请选择运输企业" clearable>
            <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
          </i-select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="searchSubmit">搜索</Button>
        </FormItem>
      </Form>
    </Card>
    <Card dis-hover :bordered="true">
      <p slot="title">列表</p>
      <p slot="extra">
        <Button type="primary" @click="addTableData" v-if="!vehicleData">添加</Button>
        <Button type="success" @click="expireDerive">导出</Button>
      </p>
      <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
    </Card>
    <Drawer :title="formTitle" v-model="formOperation" width="1000" :draggable="true" :mask-closable="false" :styles="formOperationStyles">
      <insuranceAdd v-if="formOperation" @closeFun="closeFun" :selectData="selectData"></insuranceAdd>
    </Drawer>

    <Drawer title="详情" v-model="formDetails" width="1000" :draggable="true" :styles="{'padding':'10px 10px 10px 10px'}">
      <!--保险记录-->
      <InsuranceDetails v-if="formDetails" :selectData="selectData"></InsuranceDetails>
    </Drawer>
    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>

import insuranceAdd from './insuranceAdd.vue'
import InsuranceDetails from "./InsuranceDetails.vue";
import wzTbale from "../../../components/table/table";

export default {
  props: ['vehicleData'],//接收来自父组件的数据
  components: {
    InsuranceDetails,//保险详情
    insuranceAdd,//添加
    wzTbale,//列表
  },
  data() {
    return {
      spinShow:false,//本页加载
      searchType:false,//搜索条件
      subDeptList: [],//运输企业
      dateRange: [],
      formDetails: false,
      formDataSearch: {},//搜索表单数据
      insuranceType: [],//险种字典

      formOperation: false,//表单左侧移出
      formOperationStyles: {//表单左侧移出css
        height: 'calc(100% - 51px)',
        overflow: 'auto',
        padding: '10px 10px 10px 10px',
        position: 'static'
      },


      tableData: {
        url: this.apiUrl.webApi + "/management/insurance/insurancePageList",//请求地址
        method: 'post',//请求方式
        where: {vehiclePlateNo:!!this.vehicleData ? this.vehicleData.carPlateNo:''},//搜索条件
        height: 'auto',//表格高度 auto
        page: true,//分页是否使用
        columns: [//表头数据
          {type: 'index', width: 70, align: 'center', title: '序号'},
          {title: '档案号', minWidth: 160, key: 'insuranceNumber'},
          {
            title: '营运车型', minWidth: 140, key: 'insuranceModelType', render: (h, params) => {
              return h('Tag', {
                props: {type: 'dot', color: params.row.insuranceModelType == 1 ? 'success' : 'primary'}
              }, params.row.insuranceModelType == 1 ? '运输车辆' : '货运挂车');
            }
          },
          {title: '车牌号', minWidth: 120, key: 'insuranceVehicleTrailerPlateNo'},
          {title: '车主业户', minWidth: 120, key: 'insuranceVehicleTrailerOwnerName'},
          {title: '联系电话', minWidth: 120, key: 'insuranceVehicleTrailerOwnerPhone'},
          {title: '保险年份', minWidth: 100, key: 'insuranceYearNumber'},
          {title: '保险项目', minWidth: 100, key: 'insuranceTypeValue'},
          {title: '办理日期', minWidth: 120, key: 'insuranceDate'},
          {title: '生效日期', minWidth: 120, key: 'insuranceEffectiveDate'},

          {title: '到期日期', minWidth: 120, key: 'insuranceExpireDate'},



          {title: '登记人', minWidth: 100, key: 'insuranceRegistrantName'},
          {title: '运输企业', minWidth: 240, key: 'deptName'},
          {
            title: '提醒状态', fixed: 'right', minWidth: 120, render: (h, params) => {
              return h('Tag', {
                props: {
                  type: 'dot',
                  color: (params.row.insuranceWhetherRemind == 0) ? "error" : "primary"
                }
              }, (params.row.insuranceWhetherRemind == 0) ? "关闭" :  "开启");
            }
          },
          {
            title: '到期状态', fixed: 'right', minWidth: 140, render: (h, params) => {
              return h('Tag', {
                props: {
                  type: 'dot',
                  color: (params.row.insuranceExpireState == 0) ? "error" : (params.row.insuranceExpireState == 1) ? "success" : "warning"
                }
              }, (params.row.insuranceExpireState == 0) ? "已到期" : (params.row.insuranceExpireState == 1) ? "未到期" : "即将到期");
            }
          },
          {
            title: '档案状态', fixed: 'right', minWidth: 120, render: (h, params) => {
              if(params.row.insuranceState == 1){
                return h('Tag', {props: {type: 'dot',color: "success"}},"正常");
              }else if(params.row.insuranceState == 2){
                return h('Tag', {props: {type: 'dot',color: "warning"}},"过户");
              }else if(params.row.insuranceState == 3){
                return h('Tag', {props: {type: 'dot',color: "error"}},"报废");
              }else{
                return h('Tag', {props: {type: 'dot',color: "default"}},"未知");
              }
            }
          },
          {
            title: '操作', fixed: 'right', width: 120, render: (h, params) => {
              let operationButtons = [];

              operationButtons.push(h('span', {
                style: {"color": "#2d8cf0", "cursor": "pointer"},
                on: {
                  click: () => {
                    this.selectData = JSON.parse(JSON.stringify(params.row));
                    this.formDetails = true;
                  }
                }
              }, '查看'))


              var buttonList = [];




              if(params.row.insuranceWhetherRemind == 1){//关闭
                buttonList.push(h('DropdownItem', {
                  nativeOn: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '关闭到期提醒',
                        content: '确定要关闭选中的到期提醒？',
                        onOk: () => {
                          this.remindState(params.row,0)
                        },
                        onCancel: () => {
                          //点击取消
                        }
                      });
                    }
                  }
                }, '关闭'))
              }else if(params.row.insuranceWhetherRemind == 0){//打开
                buttonList.push(h('DropdownItem', {
                  nativeOn: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '打开到期提醒',
                        content: '确定要打开选中的到期提醒？',
                        onOk: () => {
                          this.remindState(params.row,1)
                        },
                        onCancel: () => {
                          //点击取消
                        }
                      });
                    }
                  }
                }, '打开'))
              }



              //修改
              if(params.row.insuranceState == 1){
                buttonList.push(h('DropdownItem', {
                  nativeOn: {
                    click: () => {
                      this.selectData = JSON.parse(JSON.stringify(params.row));
                      this.formTitle = "修改";
                      this.formOperation = true;
                    }
                  }
                }, '修改'))
              }


              //删除
              buttonList.push(h('DropdownItem', {
                nativeOn: {
                  click: () => {
                    this.deleteInsurance(params.row);
                  }
                }
              }, '删除'))


              if (!!params.row.insurancePolicyPdf) {
                buttonList.push(h('DropdownItem', {
                  nativeOn: {
                    click: () => {
                      window.open(this.apiUrl.imgUrl + params.row.insurancePolicyPdf)
                    }
                  }
                }, '下载附件'))
              }
              if (buttonList.length > 0 && !this.vehicleData) {
                operationButtons.push(h('Divider', {props: {type: 'vertical',}}, ''))
                operationButtons.push(h('Dropdown', {props: {trigger: "hover", transfer: true}},
                  [
                    h('span', {style: {"color": "#2d8cf0", "cursor": "pointer"}}, '更多▼'),
                    h('DropdownMenu', {slot: "list"}, buttonList)
                  ])
                )
              }
              return h('div', operationButtons);
            }
          },
        ],
        format: {//返回数据格式
          list: ['data'],//数据list
          count: ['count'],//数据总量
        },
      },


      formTitle: "",//表单名称
      allKeys: [],//字典列表


    }
  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态
  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    var that = this;

    //险种字典
    that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'insurance_type'}).then(res => {
      if (!!res) {
        that.insuranceType = res.data.data;
      }
    }).catch(err => {
      console.log("失败", err)
    })
    //运输企业
    that.axios.post(that.apiUrl.coreDeptCoreDeptList, {}).then(res => {
      if (!!res) {
        that.subDeptList = res.data.data;
      }
    }).catch(err => {
      console.log("失败", err)
    })
  },
  methods: {//执行的方法
    //关闭 打开 提醒  whetherRemind   提醒状态（0：不提醒，1：数据提醒）
    remindState(data,type){
      var that = this;
      that.tableLoading = true;
      that.axios.post(that.apiUrl.webApi + "/management/insurance/insuranceCloseRemind",{uuid: data.uuid,whetherRemind:type}).then(res => {
        if (!!res) {
          that.$Message.info('操作成功');
          that.$refs.wzTbale.tableLoadData();
        }
      }).catch(err => {
        console.log("失败", err)
      })
    },
    addTableData() {//table添加
      let that = this;
      that.formTitle = "添加";
      that.selectData = {};
      that.formOperation = true;
    },
    searchSubmit() {//搜索
      this.formDataSearch.expireStartDate = !!this.dateRange[0] ? this.public.timeFormatting(this.dateRange[0], "yyyy-MM-dd") : '';
      this.formDataSearch.expireEndDate = !!this.dateRange[1] ? this.public.timeFormatting(this.dateRange[1], "yyyy-MM-dd") : '';
      this.tableData.where = JSON.parse(JSON.stringify(this.formDataSearch));
      this.$refs.wzTbale.tableLoadData(true);
    },
    //添加修改触发后关闭刷新
    closeFun(data) {
      var that = this;
      if (data) {//添加修改 刷新表单
        that.$refs.wzTbale.tableLoadData();
      }
      that.formOperation = false;
    },
    //保单删除
    deleteInsurance(data) {
      let that = this;
      that.$Modal.confirm({
        title: '删除提醒',
        content: '确定要删除选中的记录？',
        onOk: () => {
          that.spinShow = true;//显示加载
          that.axios.post(that.apiUrl.webApi + "/management/insurance/insuranceDelete", {uuid: data.uuid}).then(res => {
            that.spinShow = false;//
            if (!!res) {
              that.searchSubmit();
              that.$Message.success("删除成功");
              that.$emit("closeFun");
            }
          }).catch(err => {
            console.log("失败", err)
          })
        },
        onCancel: () => {
          //点击取消
        }
      });
    },
    //导出
    expireDerive() {
      let that = this;
      let formDataSearch = JSON.parse(JSON.stringify(this.formDataSearch));
      that.spinShow = true;
      that.axios.post(that.apiUrl.webApi + "/management/insurance/insuranceExport", formDataSearch).then(res => {
        that.spinShow = false;
        if (!!res) {
          window.open(that.apiUrl.imgUrl + res.data.data)
        }
      }).catch(err => {
        console.log("失败", err)
      })
    },
  },
  watch: {//监听

  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态

  },
  destroyed() {//destroyed 销毁完成状态

  }
}
</script>

<style lang="less">
._wz_insurance_insurance {
  display: flex;
  flex-direction: column;
}
</style>
